import { message } from 'antd';
import { queryGroupsOptions, queryGroups, del, add, detail } from '@/services/groups';

export default {
  namespace: 'groups',

  state: {
    list: [],
    pagination: {},
    current: {},
    groupsOptions: [],
  },

  effects: {
    *init({ payload }, { call, put }) {
      const groupsOptions = yield call(queryGroupsOptions);
      if (groupsOptions.httpCode === 200) {
        yield put({
          type: 'saveGroupsOptions',
          payload: groupsOptions,
        });
      } else {
        message.error({ content: groupsOptions.msg, key: 1 });
      }
      const groups = yield call(queryGroups, payload);
      if (groups.httpCode === 200) {
        yield put({
          type: 'save',
          payload: groups,
        });
      } else {
        message.error({ content: groups.msg, key: 1 });
      }
    },
    *fetch({ payload }, { call, put }) {
      const groups = yield call(queryGroups, payload);
      if (groups.httpCode === 200) {
        yield put({
          type: 'save',
          payload: groups,
        });
      } else {
        message.error({ content: groups.msg, key: 1 });
      }
    },
    *del({ payload }, { call, put }) {
      const response = JSON.parse(yield call(del, payload));
      if (response.httpCode === 200) {
        message.success(response.msg);
        yield put({ type: 'init' });
      } else {
        message.error({ content: response.msg, key: 1 });
      }
    },
    *add({ payload, form, handleModalVisible }, { call, put }) {
      const response = yield call(add, payload);
      if (response.httpCode === 200) {
        message.success(response.msg);
        form.resetFields();
        handleModalVisible();
        yield put({ type: 'init' });
      } else {
        message.error({ content: response.msg, key: 1 });
      }
    },
    *detail({ payload }, { call, put }) {
      const response = yield call(detail, payload);
      if (response.httpCode === 200) {
        yield put({
          type: 'saveDetail',
          payload: response,
        });
      } else {
        message.error({ content: response.msg, key: 1 });
      }
    },
  },

  reducers: {
    saveGroupsOptions(state, action) {
      return {
        ...state,
        groupsOptions: action.payload.data,
      };
    },
    save(state, action) {
      return {
        ...state,
        list: action.payload.data,
        pagination: {
          current: action.payload.current,
          pageSize: action.payload.size,
          total: action.payload.iTotalRecords,
        },
      };
    },
    saveDetail(state, action) {
      return {
        ...state,
        current: action.payload.data,
      };
    },
  },
};
